package com.jspica.app.messagespam;

import java.sql.SQLException;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;

public class DbManager {

	public static final String DB_NAME = "messagespam.db";
	public static final int DATABASE_VERSION = 2;

	public final Context mCtx;
	public DatabaseHelper mDbHelper;
	public SQLiteDatabase mDb;

	public DbManager(Context mCtx) {
		this.mCtx = mCtx;
		try {
			this.open();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public static final String[] DB_CREATE_JOB = new String[] {
	    "create table spam (_id INTEGER primary key autoincrement, sms_body TEXT not null, "
			+ "sender TEXT not null, time DATE)",
		"create table white (_id INTEGER primary key autoincrement, keyword TEXT not null)",
		"create table black (_id INTEGER primary key autoincrement, keyword TEXT not null)",
		"INSERT INTO white (keyword) VALUES (\"승인번호\")",
		"INSERT INTO white (keyword) VALUES (\"인증번호\")"};

	public static final String[] DB_UPDATE_JOB = new String[] {
		"create table white (_id INTEGER primary key autoincrement, keyword TEXT not null)",
		"create table black (_id INTEGER primary key autoincrement, keyword TEXT not null)",
		"INSERT INTO white (keyword) VALUES (\"승인번호\")",
		"INSERT INTO white (keyword) VALUES (\"인증번호\")"};	
		
	public void open() throws SQLException {
		mDbHelper = new DatabaseHelper(mCtx, DbManager.DB_NAME, null, DATABASE_VERSION);
		mDb = mDbHelper.getWritableDatabase();
	}

	public void close() {
		mDbHelper.close();
	}

	public class DatabaseHelper extends SQLiteOpenHelper {

		public DatabaseHelper(Context context, String name, CursorFactory factory, int version) {
			super(context, name, factory, DATABASE_VERSION);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			for (int i = 0; i < DB_CREATE_JOB.length; i++) {
				db.execSQL(DB_CREATE_JOB[i]);
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			for (int i = 0; i < DB_UPDATE_JOB.length; i++) {
				db.execSQL(DB_UPDATE_JOB[i]);
			}
		}
	}
}
